#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <math.h>
#include <linux/input.h>

int main()
{
    int fd_touch = open("/dev/input/event0", O_RDWR);
    if (fd_touch < 0)
    {
        printf("open touch error %s\n", strerror(errno));
        return -1;
    }
    printf("open touch success\n");

    // 读取触摸屏数据
    struct input_event buf;
    int x = -1, y = -1;
    while (1)
    {
        memset(&buf, 0, sizeof(buf));
        read(fd_touch, &buf, sizeof(buf));
        // printf("type = %d, code = %d, value = %d\n", buf.type, buf.code, buf.value);

        if (buf.type == EV_ABS)
        {
            if (buf.code == ABS_X)
            {
                x = buf.value * 800 / 1024;
            }
            else if (buf.code == ABS_Y)
            {
                y = buf.value * 480 / 600;
            }
        }
        // // 在按下或松开时打印坐标
        // if (buf.type == EV_KEY && buf.code == BTN_TOUCH)
        // {
        //     if (buf.value == 1)
        //     { // 按下
        //         printf("press down x = %d, y = %d\n", x, y);
        //     }
        //     else
        //     { // 松开
        //         printf("press up x = %d, y = %d\n", x, y);
        //     }
        // }
        if (buf.type == EV_SYN)
        {
            printf("x = %d, y = %d\n", x * 800 / 1024, y * 480 / 600);
        }
        // 黑色屏幕底板开发板的 显示LCD分辨率 800*480 触摸屏的分辨率1024*600
        // 蓝色屏幕底板开发板的 显示LCD分辨率 800*480 触摸屏的分辨率800*480
    }

    close(fd_touch);
    return 0;
}
/*

// 第一次触摸
type: 3, code: 0, value: 84
type: 3, code: 1, value: 41
type: 1, code: 330, value: 1
type: 0, code: 0, value: 0
type: 1, code: 330, value: 0
type: 0, code: 0, value: 0

// 第二次触摸
type: 3, code: 0, value: 877
type: 3, code: 1, value: 438
type: 1, code: 330, value: 1
type: 0, code: 0, value: 0
type: 1, code: 330, value: 0
type: 0, code: 0, value: 0


// 按住不放
type: 3, code: 0, value: 216
type: 3, code: 1, value: 276
type: 1, code: 330, value: 1
type: 0, code: 0, value: 0



Event types
    type EV_ABS=3  绝对位移  屏幕触摸
        code ABS_X=0 x轴
        code ABS_Y=1 y轴

    type EV_KEY=1  按键键盘
        code BTN_TOUCH=330  value=1按下 value=0松开
    type EV_SYN=0  事件分割
*/
